﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mortgage.DAL.Entity;
using System.Web.Security;
using Mortgage.Srv.Cls;
using Mortgage.UserControl;

namespace Mortgage.Form
{
    public partial class MortgageUI : System.Web.UI.Page
    {

        Mortgage.Srv.IInterestRateSrv svcInter = Mortgage.Srv.SrvFactory.CreateInterestRateSrv();
        Mortgage.Srv.IMortgageSrv svcMortgage = Mortgage.Srv.SrvFactory.CreateMortgageSrv();


        protected void Page_Load(object sender, EventArgs e)
        {

            fldInterID.SelectedIndexChanged += new EventHandler(fldInterID_SelectedIndexChanged);
            grid.RowDataBound += new GridViewRowEventHandler(grid_RowDataBound);


            if (!Page.IsPostBack)
            {

                BlankFilterControl();
                BindMortgageStatus();
                BindMortgageStatusFilter();
                RefreshDataGrid();

                FormModeMorgate = EnmFormMode.Blank;
                HandleFormStateMortgate(FormModeMorgate);
            }
            else 
            {
                RefreshDataGrid();
            }


        }

        protected void RefreshDataGrid()
        {
            string no, cusName, itmName;
            no = fldFltSerialNo.Text;
            cusName = fltFltCustomerName.Text;
            itmName = fldFltItemName.Text;
            int? st = null;
            if (fldFltStatus.SelectedIndex > 0)
                st = Convert.ToInt32(fldFltStatus.Text);

            DateTime? dteNo = null;
            DateTime dt = new DateTime();
            if (!string.IsNullOrEmpty(fldFltMortdate.Text))
            {
                Utility.ParseDateTime(fldFltMortdate.Text, out dt);
                dteNo = dt;
            }

            DateTime? dteEnd = null;
            DateTime dtEndV = new DateTime();
            if (!string.IsNullOrEmpty(fldFltMordateEnd.Text))
            {
                Utility.ParseDateTime(fldFltMordateEnd.Text, out dtEndV);
                dteEnd = dtEndV;
            }
            int totalResult = 0;

            List<vwMortgageInfo> dtResult = svcMortgage.Find( Utility.AgentId, no, dteNo, dteEnd, cusName, itmName, st, grid.PageSize, grid.PageIndex, out totalResult);

            custPager.TotalPages = (totalResult / grid.PageSize) + 1;
            custPager.CurrentPageSize = grid.PageSize;
            custPager.CurrentPageNumber = grid.PageIndex;

            grid.DataSource = dtResult;
            grid.DataBind();
        }

        #region Event mortgage handler

        void grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
                e.Row.Attributes["onmouseout"] = "this.style.cursor='default';";

                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grid, "Select$" + e.Row.RowIndex);
            }
        }

        protected void grid_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(grid.DataKeys[grid.SelectedIndex].Value.ToString());
            tMortgage mortgage = svcMortgage.GetById(id);
            if (mortgage == null)
                EntityMorgate = new tMortgage();
            else
                EntityMorgate = mortgage;

            // Update mode
            FormModeMorgate = EnmFormMode.View;
            HandleFormStateMortgate(FormModeMorgate);
            BindViewMortgage();
        }

        void fldInterID_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(fldInterestRate.Text))
            {
                int id = Convert.ToInt32(fldInterID.SelectedValue);
                tInterestRate intRate = svcInter.GetById(id);
                if (intRate != null)
                {
                    fldInterestRate.Text = intRate.InterestRate.ToString();
                    fldNumDayExpire.Text = intRate.NumOfDayExpire.ToString();
                }
            }
        }

        protected void custPager_PageChanged(object sender, CustomPageChangeArgs e)
        {
            grid.PageSize = e.CurrentPageSize;
            grid.PageIndex = e.CurrentPageNumber - 1;

            RefreshDataGrid();
        }

        protected void btnFilter_Click(object sender, EventArgs e)
        {
            RefreshDataGrid();
        }

        protected void btnCancelMortgage_Click(object sender, EventArgs e)
        {
            FormModeMorgate = EnmFormMode.Blank;
            HandleFormStateMortgate(FormModeMorgate);
        }

        protected void btnDeleteMortgage_Click(object sender, EventArgs e)
        {
            BindEntityMortgage();
            svcMortgage.Delete(EntityMorgate);
            RefreshDataGrid();
            FormModeMorgate = EnmFormMode.Blank;
            HandleFormStateMortgate(FormModeMorgate);
        }

        protected void btnStatusMortgage_Click(object sender, EventArgs e)
        {
            Button raiser = sender as Button;
            BindEntityMortgage();

            int argStatus = Convert.ToInt32(raiser.CommandArgument);

            int result = svcMortgage.ChangeStatus(EntityMorgate, argStatus);

            if (result == 0)
            {
                RefreshDataGrid();
                EntityMorgate.Status = argStatus;
                BindViewMortgage();
                EntityMorgate.Status = argStatus;
                DialogMessMortgage.Text = "Cập nhật thành công!";
            }
            else
            {
                DialogMessMortgage.Text = "Failure thay đổi trạng thái khôngthành công!";
            }
        }

        protected void btnNewMortgage_Click(object sender, EventArgs e)
        {
            // Update mode


            EntityMorgate = new tMortgage() { ID = 0, MorDate = DateTime.Now };
            FormModeMorgate = EnmFormMode.Insert;
            HandleFormStateMortgate(FormModeMorgate);

            int serialNo = 0;
            int.TryParse(EntityMorgate.SerialNo, out serialNo);

            serialNo++;
            EntityMorgate.SerialNo = serialNo.ToString();

            BindViewMortgage();
        }

        protected void btnSaveMortgage_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;
            BindEntityMortgage();
            // clear error Message
            DialogMessMortgage.Text = string.Empty;
            DialogMessMortgage.CssClass = "successBox";
            int result;
            if (FormModeMorgate == EnmFormMode.Insert) // Insert Mode
            {

                try
                {
                    result = svcMortgage.Insert(EntityMorgate);
                    switch (result)
                    {
                        case 0:
                            DialogMessMortgage.Text = "Cập nhật thành công!";
                            RefreshDataGrid();

                            // Translate to update mode
                            // Update mode
                            if (chkKeepInsert.Checked)
                            {
                                FormModeMorgate = EnmFormMode.Insert;
                                EntityMorgate = new tMortgage();
                                HandleFormStateMortgate(FormModeMorgate);
                                BindViewMortgage();
                            }
                            else
                            {
                                FormModeMorgate = EnmFormMode.Edit;
                                HandleFormStateMortgate(FormModeMorgate);
                                BindViewMortgage();
                            }
                            break;
                        case 2:
                            DialogMessMortgage.Text = "Số hóa đơn đã tồn tại";
                            DialogMessMortgage.CssClass = "failureBox";
                            break;

                    }

                }
                catch (Exception ex)
                {
                    DialogMessMortgage.Text = ex.Message;
                    DialogMessMortgage.CssClass = "failureBox";
                }


            }
            else
            {
                result = svcMortgage.Update(EntityMorgate);
                switch (result)
                {
                    case 0:
                        DialogMessMortgage.Text = "Cập nhật thành công!";
                        //BindGridView();

                        // Translate to update mode
                        // Update mode
                        FormModeMorgate = EnmFormMode.Edit;
                        HandleFormStateMortgate(FormModeMorgate);
                        BindViewMortgage();
                        break;
                    case 2:
                        DialogMessMortgage.Text = "Số hóa đơn đã tồn tại";
                        DialogMessMortgage.CssClass = "failureBox";
                        break;

                }
            }
            BlankFilterControl();
            RefreshDataGrid();
        }

        protected void btnEditMortgage_Click(object sender, EventArgs e)
        {
            BindEntityMortgage();
            FormModeMorgate = EnmFormMode.Edit;
            HandleFormStateMortgate(FormModeMorgate);

        }

        #endregion

        #region Property Mortgage

        public tMortgage EntityMorgate
        {
            get;
            set;
        }

        public EnmFormMode FormModeMorgate
        {
            get
            {
                if (ViewState["_ViewStateMorgate"] == null)
                    return EnmFormMode.Blank;
                EnmFormMode result = (EnmFormMode)Enum.Parse(typeof(EnmFormMode), ViewState["_ViewStateMorgate"].ToString());
                return result;

            }
            set
            {
                ViewState["_ViewStateMorgate"] = value;
            }
        }

        #endregion

        #region Bind Mortgage function

        void BindMortgageStatus()
        {
            lstStatus.DataSource = Utility.GetMortgageStatus();
            lstStatus.DataBind();
        }

        void BindMortgageStatusFilter()
        {
            fldFltStatus.DataSource = Utility.GetMortgageStatus();
            fldFltStatus.DataBind();

        }

        void BindInterestTalbe(DropDownList drpInterest)
        {

            if (drpInterest.Items.Count == 1)
            {
                drpInterest.DataSource = svcInter.GetConfigIntestName();
                drpInterest.DataBind();
            }

        }

        void BindBillDataGrid()
        {
            if (EntityMorgate != null)
            {
                List<tBill> source = Mortgage.Srv.SrvFactory.CreateBillSrv().GetByMortgageId(EntityMorgate.ID);
                gridBill.DataSource = source;
                gridBill.DataBind();


            }
        }

        protected void HandleFormStateMortgate(EnmFormMode state)
        {
            switch (state)
            {
                case EnmFormMode.Blank:

                    btnCancel.Enabled = false;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = true;
                    btnSave.Enabled = false;
                    btnEdit.Enabled = false;
                    hplBill.Visible = false;
                    BlankControlMortgage();
                    EnableControlMortgage(false);
                    EntityMorgate = new tMortgage();

                    break;
                case EnmFormMode.Edit:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = true;
                    btnEdit.Enabled = false;
                    hplBill.Visible = true;
                    EnableControlMortgage(true);
                    if (gridBill.Rows.Count <= 0)
                        btnDelete.Enabled = false;
                    //fldStartDate.Enabled = false; // Edit can not delete

                    break;
                case EnmFormMode.Insert:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = false;
                    btnSave.Enabled = true;
                    btnEdit.Enabled = false;
                    hplBill.Visible = false;
                    EnableControlMortgage(true);

                    lstStatus.Enabled = false;
                    break;
                case EnmFormMode.View:
                    btnCancel.Enabled = false;
                    btnDelete.Enabled = true;
                    btnNew.Enabled = true;
                    btnSave.Enabled = false;
                    btnEdit.Enabled = true;
                    hplBill.Visible = true;
                    EnableControlMortgage(false);
                    if (gridBill.Rows.Count <= 0)
                        btnDelete.Enabled = false;
                    break;
                //case EnmFormMode.
            }

            BindViewMortgage();
        }

        protected void EnableControlMortgage(bool enable)
        {

            fldCustomerPhone.Enabled = enable;
            fldCustumerAddress.Enabled = enable;
            fldCustumerName.Enabled = enable;
            fldDescription.Enabled = enable;
            fldInterestRate.Enabled = enable;
            fldInterID.Enabled = enable;
            fldItemName.Enabled = enable;
            fldMorDate.Enabled = enable;
            fldMorMoney.Enabled = enable;
            fldSerialNo.Enabled = enable;
            fldNumDayExpire.Enabled = enable;
            lstStatus.Enabled = enable;

        }

        protected void BindViewMortgage()
        {

            fldInterID.SelectedIndex = 0;
            BindInterestTalbe(fldInterID);
            if (EntityMorgate.Inter_ID.HasValue)
                fldInterID.SelectedValue = EntityMorgate.Inter_ID.GetValueOrDefault().ToString();
            else
                fldInterID.SelectedValue = (-1).ToString();


            fldInterestRate.Text = EntityMorgate.InterestRate.ToString();

            fldCustomerPhone.Text = EntityMorgate.CustomerPhone;
            fldCustumerAddress.Text = EntityMorgate.CustomerAddress;
            fldCustumerName.Text = EntityMorgate.CustomerName;
            fldDescription.Text = EntityMorgate.ItemDescription;
            fldItemName.Text = EntityMorgate.ItemName;

            fldMorDate.Text = Utility.FormatDateTime(EntityMorgate.MorDate.GetValueOrDefault());
            fldMorMoney.Text = (EntityMorgate.MorMoney / 1000).ToString();
            fldSerialNo.Text = EntityMorgate.SerialNo;

            fldNumDayExpire.Text = EntityMorgate.NumDayExpire.ToString();

            fldID.Value = EntityMorgate.ID.ToString();
            fldEnmInterRateType.Value = EntityMorgate.EnmInterestRateType.GetValueOrDefault().ToString();

            fldStatusId.Value = EntityMorgate.Status.ToString();
            fldStatus.Text = Utility.GetMorgageStatusCode(EntityMorgate.Status);

            hplBill.NavigateUrl = @"BillUI.aspx?MorgId=" + EntityMorgate.ID;

            BindBillDataGrid();

        }

        protected void BindEntityMortgage()
        {
            tMortgage entity = new tMortgage();
            if (EntityMorgate != null)
                entity.ID = EntityMorgate.ID;

            int id = 0;
            int.TryParse(fldID.Value, out id);
            entity.ID = id;
            entity.Inter_ID = Convert.ToInt32(fldInterID.SelectedItem.Value);
            if (entity.Inter_ID == -1)
                entity.Inter_ID = null;


            entity.SerialNo = fldSerialNo.Text;

            entity.CustomerPhone = fldCustomerPhone.Text;
            entity.CustomerAddress = fldCustumerAddress.Text;
            entity.CustomerName = fldCustumerName.Text;

            entity.ItemDescription = fldDescription.Text;

            if (string.IsNullOrEmpty(fldInterestRate.Text))
                entity.InterestRate = null;
            else
                entity.InterestRate = Convert.ToDecimal(fldInterestRate.Text);

            entity.NumDayExpire = Convert.ToInt32(fldNumDayExpire.Text);
            entity.ItemName = fldItemName.Text;

            DateTime dteMorDate = new DateTime();
            if (Utility.ParseDateTime(fldMorDate.Text, out dteMorDate) == 0)
                entity.MorDate = dteMorDate;
            else
            {
                // Raise error
            }

            entity.MorMoney = Convert.ToDecimal(fldMorMoney.Text) * 1000;
            entity.ItemDescription = fldDescription.Text;
            if (!string.IsNullOrEmpty(fldEnmInterRateType.Value))
                entity.EnmInterestRateType = Convert.ToInt32(fldEnmInterRateType.Value);
            entity.Status = Convert.ToInt32(fldStatusId.Value);
            EntityMorgate = entity;
            BindPropertyMortgage();
        }

        protected void BlankFilterControl()
        {
            fldFltItemName.Text = string.Empty;
            fldFltMortdate.Text = string.Empty;
            fldFltMordateEnd.Text = string.Empty;
            fltFltCustomerName.Text = string.Empty;
            fldFltStatus.SelectedIndex = 0;
            fldFltSerialNo.Text = string.Empty;
        }

        protected void BlankControlMortgage()
        {

            fldCustomerPhone.Text = string.Empty;
            fldCustumerAddress.Text = string.Empty;
            fldCustumerName.Text = string.Empty;
            fldDescription.Text = string.Empty;
            fldInterestRate.Text = string.Empty;
            fldInterID.SelectedValue = "-1";
            BindInterestTalbe(fldInterID);

            fldItemName.Text = string.Empty;
            fldMorDate.Text = string.Empty;
            fldMorMoney.Text = string.Empty;
            fldSerialNo.Text = string.Empty;

            fldStatus.Text = "<<None>>";
            fldStatusId.Value = string.Empty;

            DialogMessMortgage.CssClass = string.Empty;
            DialogMessMortgage.Text = string.Empty;

        }

        protected void BindPropertyMortgage()
        {
            MembershipUser membershipUser = System.Web.Security.Membership.GetUser();

            if (membershipUser != null)
            {
                EntityMorgate.CreatedBy = membershipUser.UserName;
                EntityMorgate.ModifiedBy = membershipUser.UserName;
                EntityMorgate.CreatedDate = DateTime.Now;
                EntityMorgate.ModifiedDate = DateTime.Now;

                EntityMorgate.Age_ID = Utility.AgentId;

            }

        }

        #endregion

    }
}